Ext.define('Jason.view.main.ViewportController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.mainviewport',
	init : function(){
		var me = this;
		EUtil.initAccount();
		Ext.setGlyphFontFamily('FontAwesome'); //指定矢量图字体
		EUtil.initCfg();
		if(Ext.isIE8m){
			EUtil.showMsg({
				message : '为了您更好的体验，请使用chrome浏览器或Firefox浏览器'
			});
		}
		try{
			me.getView().down('#navigationTreeList').getStore().load();
		}catch(e){}
		//重置变量
		Ext.Viewport = this.getView();
		Ext.FramePanel = Ext.Viewport.items.items[1];
		/**
		 * 禁用浏览器自带右键
		 */
		Ext.getDoc().on("contextmenu", function(e){  
		    e.stopEvent();  
		}); 
	},

    listen : {
        controller : {
            '#' : {
                unmatchedroute : 'onRouteChange'
            }
        }
    },

    routes: {
        ':node': 'onRouteChange'
    },

    setCurrentView: function(hashTag) {
        hashTag = (hashTag || '');//.toLowerCase();
        var me = this,
            refs = me.getReferences(),
            mainCard = refs.mainCardPanel,
            mainLayout = mainCard.getLayout(),
            navigationList = refs.navigationTreeList,
            viewModel = me.getViewModel(),
            vmData = viewModel.getData(),
            store = navigationList.getStore(),
            node = store.findNode('routeId', hashTag),
            view = node ? node.get('view') : hashTag,//如果没有找到则使用原有的
            lastView = vmData.currentView,
            existingItem = mainCard.child('component[routeId=' + hashTag + ']'),
            newView;
        //设置面包屑导航
        viewModel.set('selectedNodeByBreadcrumb',navigationList.getStore().findNode('extendtype',hashTag));
        if (lastView && lastView.isWindow) {
            lastView.destroy();
        }

        lastView = mainLayout.getActiveItem();
		if(hashTag === 'userCenter'){ /* 如果用户进入到是用户中心 */
			view = 'protal.authentication.UserCenter';
		}
        if (!existingItem) {
			if(!view)//如果为空的情况下直接跳转到看板页面
				return;
            try{
            	newView = Ext.create('Jason.view.' + (view || 'protal.pages.Error404Window'), {
                    hideMode: 'offsets',
					margin : 3,
                    routeId: hashTag
            	});
            }catch(e){
            	console.error(e);
//            	EUtil.showMsg({
//            		title:'系统提示',
//            		message:'系统访问路径配置错误，请联系管理员；<br />错误信息：<i style="color:red;">'+e+'</i>'
//        		});
//            	return;
            }
        }

        if (!newView || !newView.isWindow) {
            if (existingItem) {
                if (existingItem !== lastView) {
                    mainLayout.setActiveItem(existingItem);
                }
                newView = existingItem;
            }
            else {
                Ext.suspendLayouts();
                mainLayout.setActiveItem(mainCard.add(newView));
                Ext.resumeLayouts(true);
            }
        }

        navigationList.setSelection(node);

        if (newView.isFocusable(true)) {
            newView.focus();
        }

        vmData.currentView = newView;
    },
	/**
	 * 点击树节点跳转页面
	 * @param tree	输结构
	 * @param node	点击节点
     */
    onNavigationTreeSelectionChange: function (tree, node) {
        try{
        	if (node && node.get('view')) {
                this.redirectTo( node.get("routeId"));
            }else{
    			if(node.get('redirect')){
    				window.location.href = window.location.origin + window.location.pathname + '?' + node.get("routeId");
    			}else{
    				// EUtil.toast('缺少路由配置',2);
    			}
    		}
        }catch(e){}
    },

    onToggleNavigationSize: function () {
        var me = this,
            refs = me.getReferences(),
            navigationList = refs.navigationTreeList,
            wrapContainer = refs.mainContainerWrap,
            collapsing = !navigationList.getMicro(),
            new_width = collapsing ? 64 : 250;

        if (Ext.isIE9m || !Ext.os.is.Desktop) {
            Ext.suspendLayouts();
            refs.senchaLogo.setWidth(new_width);
            navigationList.setWidth(new_width);
            navigationList.setMicro(collapsing);
            Ext.resumeLayouts();
            wrapContainer.layout.animatePolicy = wrapContainer.layout.animate = null;
            wrapContainer.updateLayout();
        }
        else {
            if (!collapsing) {
                navigationList.setMicro(false);
            }
            refs.senchaLogo.animate({dynamic: true, to: {width: new_width}});
            navigationList.width = new_width;
            wrapContainer.updateLayout({isRoot: true});
            if (collapsing) {
                navigationList.on({
                    afterlayoutanimation: function () {
                        navigationList.setMicro(true);
                    },
                    single: true
                });
            }
        }
    },

    onMainViewRender:function() {
		var self = this;
		if (!window.location.hash) {
			//self.redirectTo("dashboard");
			//这里可以控制登陆相关
			if(session.get('loginState') === undefined || session.get('loginState') === false){
				this.redirectTo("authentication.Login");
			}else{
				this.redirectTo("dashboard");
			}
		}
    },

    onRouteChange:function(id){
        var self = this;
		Ext.defer(function(){/** 延迟加载主要解决问题是右侧菜单资源还为加载完成页面展示会有问题*/
			self.setCurrentView(id);
		},800);
    },

    onSearchRouteChange: function () {
        this.setCurrentView('search');
    },

    onEmailRouteChange: function () {
        this.setCurrentView('email');
    },
	onShowSetting : function(btn){
		var me = this;
		var setting = Ext.create('Ext.menu.Menu',{
			margin: '0 0 10 0',
			items: [{
				iconCls : 'fa fa-user',
				href : '#userCenter',
				text: '个人中心'
			},{
				iconCls : 'fa fa-cog',
				handler : me.systemSetting,
				text: '设置'
			},'-',{
				iconCls : 'fa fa-sign-out',
				text: '安全退出',
				handler : function(self){
					EUtil.showMsg({
						option:3,
						title : '退出系统',
						message : '您确认要退出系统？',
						callback : function(btn){
							if(btn === 'ok'){
								EUtil.RS({
									url: reqUrl.sys.logout,
									callback: function(result) {
										if(result.success){
											session.set('loginState',false);
											window.location.href = window.location.origin + window.location.pathname || '';
											//me.redirectTo("authentication.login");
										}else{
											EUtil.toast(result.msg_info,2);
										}
									}
								});
							}
						}
					});
				}
			}]
		});
		setting.showAt(btn.getX(),btn.getY()+35);
	},
	/**
		显示站内搜索输入框
	*/
	onLocalSearch : function(btn){
		var localSearchInput = btn.up('toolbar').down('#localSearchInput');
		localSearchInput.on('blur',function(self){self.hide();});
		localSearchInput.show();
		localSearchInput.focus();
	},
	systemSetting : function(btn){
		var settingModel = Ext.widget({
			xtype: "pushWindow",
			showWidth:300,
			item : {xtype : 'settingForm'}
		});
		settingModel.showAt(Ext.getBody().getWidth()-200,65);
	},
	onShowNotice : function(btn){
		Ext.create('Ext.menu.Menu',{
				items : Ext.create('Ext.tab.Panel',{
				width:366,
				ui : 'navigation',
				listeners : {
					render:function(tabPanel){
						Ext.Array.each(tabPanel.items.items,function(item){
							item.setWidth(122);
						})
					}
				},
				dockedItems : [{
					 xtype: 'toolbar',
					 dock: 'bottom',
					 items : ['->',{text:'<b>清空列表</b>'},'->']
				}],
				items : [
					{title:'&nbsp;&nbsp;&nbsp;通知(5)&nbsp;&nbsp;',xtype:'articleList',bind:'{articleListStore}'},
					{title:'&nbsp;&nbsp;&nbsp;消息(5)&nbsp;&nbsp;',xtype:'articleList',bind:'{articleListStoreMsg}'},
					{title:'&nbsp;&nbsp;&nbsp;代办(2)&nbsp;&nbsp;',xtype:'articleList',bind:'{articleListStoreDb}'}
				]
			})
		}).showAt(btn.getX()-160,btn.getY()+25);
	},
	/**
	 * 开启全屏模式
	 */
	onEnabledFullScreen : function(btn){
		if(!btn.fullScreen){/** 全屏  */
			btn.fullScreen = true;
			btn.tooltip = "退出全屏";
			var docElm = document.documentElement;
			if (docElm.requestFullscreen) {
				docElm.requestFullscreen();
			} else if (docElm.mozRequestFullScreen) {
				docElm.mozRequestFullScreen();
			} else if (docElm.webkitRequestFullScreen) {
				docElm.webkitRequestFullScreen();
			} else if (docElm.msRequestFullscreen) {
				docElm.msRequestFullscreen();
			}
		}else{	/** 退出全屏*/
			btn.tooltip = "开启全屏";
			btn.fullScreen = false;
			if (document.exitFullscreen) {
				document.exitFullscreen();
			} else if (document.mozCancelFullScreen) {
				document.mozCancelFullScreen();
			} else if (document.webkitCancelFullScreen) {
				document.webkitCancelFullScreen();
			} else if (document.msExitFullscreen) {
				document.msExitFullscreen();
			}
		}
	},
 	/**
 	 * 改变系统主题
 	 */
 	onChangeTheme : function(btn){
 		localStorage.setItem("style",btn.code);
		EUtil.onAppUpdate();
 	}
});
